package com.teamit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.teamit.entity.Goal;
import com.teamit.entity.Task;
import com.teamit.util.db.DBHelp;
import com.teamit.util.db.RowMapper;

public class GoalDao {
	
	DBHelp<Goal> db = new DBHelp<Goal>();
	
	
	public void save(Goal goal){
		String sql = "insert into t_goal(id,`name`,`desc`,createtime,employee_id,project_id) values(?,?,?,?,?,?)";
		System.out.println("-------------");
		System.out.println(goal.getEmployeeid());
		db.executeSQL(sql, goal.getId(),goal.getName(),goal.getDesc(),goal.getCreatetime(),goal.getEmployeeid(),goal.getProjectid());
	}
	public void update(Goal goal){
		String sql = "update t_goal set `name`=?,`desc`=?,createtime=?,employee_id=?,project_id=? where id=?";
		db.executeSQL(sql, goal.getName(),goal.getDesc(),goal.getCreatetime(), goal.getEmployeeid(),goal.getProjectid(),goal.getId());
	}
	public List<Goal> findByProjectId(String projectid){
		String sql = "SELECT tg.id,tg.name,tg.desc,tg.createtime,tg.employee_id,tg.project_id,rate,SUM(rate),count(rate) FROM t_goal AS tg LEFT JOIN t_task AS tt ON tg.id=tt.goal_id where project_id=? GROUP BY tg.name";
		return db.executeQueryToList(sql, new RowMapper<Goal>(){
			public Goal mapRow(ResultSet rs) throws SQLException {
				Goal goal = new Goal();
				goal.setId(rs.getString("id"));
				goal.setName(rs.getString("name"));
				goal.setDesc(rs.getString("desc"));
				goal.setCreatetime(rs.getString("createtime"));
				goal.setEmployeeid(rs.getString("employee_id"));
				goal.setProjectid(rs.getString("project_id"));
				
				Task task = new Task();
				task.setRate(rs.getInt("sum(rate)"));
				task.setCount(rs.getInt("count(rate)"));
				goal.setTask(task);
				
				return goal;
			}
		},projectid);
		
	}
	public Goal findById(String id){
		String sql = "SELECT tg.id,tg.name,tg.desc,tg.createtime,tg.employee_id,tg.project_id ,SUM(rate),COUNT(rate) FROM t_goal AS tg LEFT JOIN t_task AS tt ON tg.id=tt.goal_id  WHERE tg.id=?";

		return db.executeQueryToObject(sql, new GoalRowMapper(), id);
	}
	
	private class GoalRowMapper implements RowMapper<Goal>{

		public Goal mapRow(ResultSet rs) throws SQLException {
			Goal goal = new Goal();
			goal.setId(rs.getString("id"));
			goal.setName(rs.getString("name"));
			goal.setDesc(rs.getString("desc"));
			goal.setCreatetime(rs.getString("createtime"));
			goal.setEmployeeid(rs.getString("employee_id"));
			goal.setProjectid(rs.getString("project_id"));
			
			Task task = new Task();
			task.setCount(rs.getInt("count(rate)"));
			task.setRate(rs.getInt("sum(rate)"));
			
			goal.setTask(task);
			return goal;
		}
		
	}

}
